<template>
  <div class="gift-page">
    <div class="gift-content">
      <div class="gift-icon">
        <img src="@/assets/images/user/icn05.png" alt="Gift" />
      </div>
      <div class="gift-title">{{ t("profile_gift") }}</div>

      <div class="gift-form">
        <input
          type="text"
          v-model="giftCode"
          :placeholder="t('user-gift_inputPlaceholder')"
          class="gift-input"
        />

        <button
          @click="receiveGift"
          :disabled="isSubmitting"
          class="redeem-btn"
        >
          {{ isSubmitting ? t("settle_processing") : t("user-gift_redeemBtn") }}
        </button>

        <!-- <div class="gift-tips">
          <div class="tip-icon">▲</div>
          <div class="tip-text">
            Jumlah hadiah juga dapat ditarik atau digunakan untuk membeli perangkat.
          </div>
        </div> -->
      </div>

      <!-- 兑换记录 -->
      <div class="gift-records">
        <div class="record-title">{{ t("gift_records") }}</div>

        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <div>{{ t("user-coupon_memuat") }}</div>
        </div>

        <div v-else-if="giftRecords.length > 0" class="record-list">
          <div
            v-for="(record, index) in giftRecords"
            :key="index"
            class="record-item"
          >
            <div class="record-info">
              <div class="record-date">{{ record.wdate }}</div>
            </div>
            <div class="record-amount">{{ formatCurrency(record.number) }}</div>
          </div>
        </div>

        <div v-else class="no-data">
          <div class="no-data-text">{{ t("user-coupon_noData") }}</div>
        </div>

        <div v-if="giftRecords.length > 0 && hasMore" class="load-more">
          <button
            @click="loadMore"
            :disabled="loadingMore"
            class="load-more-btn"
          >
            {{ loadingMore ? t("user-coupon_memuat") : t("gift_more") }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 导入所需的依赖
import { getGiftRecords, redeemGift } from "@/api/user";
import { closeToast, showToast } from "vant";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

// 定义API响应类型接口
interface ApiResponse {
  msg: string;
  code: number;
  data: any;
  count?: number;
}

// 定义礼品记录接口
interface GiftRecord {
  number: string; // 领取金额
  wdate: string; // 兑换时间
  redCode: string; // 兑换码
}

// 初始化数据
const router = useRouter();
const giftCode = ref("");
const isSubmitting = ref(false);
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(false);
const page = ref(1);
const limit = 10;
const giftRecords = ref<GiftRecord[]>([]);
const { t } = useI18n();
// 格式化货币
function formatCurrency(value: number | string): string {
  const numValue = typeof value === "string" ? parseFloat(value || "0") : value;
  return "COP " + numValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 获取礼品兑换记录
async function fetchGiftRecords(isLoadMore = false) {
  if (isLoadMore) {
    if (loadingMore.value) return;
    loadingMore.value = true;
    page.value++; // 加载更多时递增页码
  } else {
    if (loading.value) return;
    loading.value = true;
    page.value = 1;
    giftRecords.value = [];
  }

  try {
    const result = await getGiftRecords({
      page: page.value,
      limit,
    });

    const response = result as unknown as ApiResponse;

    if (response && (response.code === 0 || response.code === 200)) {
      // 直接获取data数组作为记录列表
      const records = Array.isArray(response.data) ? response.data : [];

      if (isLoadMore) {
        giftRecords.value = [...giftRecords.value, ...records];
      } else {
        giftRecords.value = records;
      }

      // 根据count字段判断是否有更多数据
      const totalCount = response.count || 0;
      hasMore.value = giftRecords.value.length < totalCount;

      // 如果没有数据返回，回退页码
      if (isLoadMore && records.length === 0) {
        page.value--;
      }
    }
  } catch (error) {
    console.error("err:", error);

    // 发生错误时，如果是加载更多，回退页码
    if (isLoadMore) {
      page.value--;
    }
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
}

// 加载更多
function loadMore() {
  fetchGiftRecords(true);
}

// 方法定义
async function receiveGift() {
  if (!giftCode.value.trim()) {
    showToast(t("user-gift_inputPlaceholder"));
    return;
  }

  // 防止重复提交
  if (isSubmitting.value) return;
  isSubmitting.value = true;

  try {
    showToast({
      type: "loading",
      message: t("settle_processing"),
      forbidClick: true,
      duration: 0,
    });

    // 调用API兑换礼品
    const result = await redeemGift(giftCode.value.trim());
    const response = result as unknown as ApiResponse;

    closeToast();

    if (response && (response.code === 0 || response.code === 200)) {
      showToast({
        type: "success",
        message: response.msg || t("gift_success"),
      });

      // 清空输入框
      giftCode.value = "";

      // 刷新兑换记录
      fetchGiftRecords();
    } else {
      showToast({
        type: "fail",
        message: response.msg || t("gift_err"),
      });
    }
  } catch (error: any) {
    closeToast();
    console.error("兑换礼品出错:", error);
    showToast({
      type: "fail",
      message: error?.message || t("gift_err"),
    });
  } finally {
    isSubmitting.value = false;
  }
}

// 生命周期钩子
onMounted(() => {
  // 获取礼品兑换记录
  fetchGiftRecords();
});
</script>

<style lang="less" scoped>
.gift-page {
  min-height: 100vh;
  padding: 20px;
  background: url("@/assets/images/user/Topbg.png") no-repeat center center;
  background-size: 100% auto;
}

.gift-content {
  width: 100%;
  max-width: 395px;
  padding: 0 17px 20px;
  background: linear-gradient(
    180deg,
    rgba(254, 242, 230, 0) 4%,
    rgba(254, 237, 221, 0.1) 63%
  );
  margin: 100px auto 0;
  border-radius: 10px;
}

.gift-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;

  img {
    width: 80px;
    height: 80px;
    display: block;
    margin: 0 auto;
    transform: translateY(-30px);
  }
}

.gift-title {
  font-size: 18px;
  color: #f6e0ca;
  margin-bottom: 25px;
  font-weight: 500;
  text-align: center;
  margin-top: -20px;
}

.gift-form {
  width: 100%;
  margin-bottom: 20px;
}

.gift-input {
  width: 100%;
  height: 50px;
  background-color: rgba(25, 22, 21, 0.6);
  border: none;
  border-radius: 8px;
  color: #f6e0ca;
  font-size: 14px;
  padding: 0 15px;
  margin-bottom: 15px;
  outline: none;

  &::placeholder {
    color: rgba(246, 224, 202, 0.5);
  }
}

.redeem-btn {
  width: 100%;
  height: 50px;
  background-color: #f6e0ca;
  border: none;
  border-radius: 8px;
  color: #332b27;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  cursor: pointer;

  &:active {
    opacity: 0.9;
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.gift-tips {
  background: linear-gradient(
    90deg,
    rgba(254, 229, 207, 0),
    rgba(223, 182, 149, 0.2) 99%
  );
  border-radius: 8px;
  padding: 15px;
  display: flex;

  .tip-icon {
    color: #f8969a;
    margin-right: 10px;
    font-size: 12px;
  }

  .tip-text {
    flex: 1;
    font-size: 12px;
    line-height: 1.4;
    color: rgba(246, 224, 202, 0.8);
  }
}

/* 兑换记录样式 */
.gift-records {
  margin-top: 20px;
  border-top: 1px solid rgba(246, 224, 202, 0.2);
  padding-top: 15px;
}

.record-title {
  font-size: 16px;
  color: #f6e0ca;
  margin-bottom: 15px;
  font-weight: 500;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: rgba(246, 224, 202, 0.6);
  font-size: 14px;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 2px solid rgba(246, 224, 202, 0.2);
  border-top: 2px solid #f6e0ca;
  border-radius: 50%;
  margin-bottom: 10px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.record-list {
  margin-bottom: 15px;
}

.record-item {
  background-color: rgba(30, 27, 26, 0.6);
  border-radius: 8px;
  padding: 12px 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-info {
  .record-code {
    font-size: 14px;
    color: #f6e0ca;
    margin-bottom: 5px;
  }

  .record-date {
    font-size: 12px;
    color: rgba(246, 224, 202, 0.6);
  }
}

.record-amount {
  font-size: 16px;
  color: #f8969a;
  font-weight: 500;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.no-data-text {
  color: rgba(246, 224, 202, 0.6);
  font-size: 14px;
}

.load-more {
  text-align: center;
  margin-top: 15px;
}

.load-more-btn {
  background: transparent;
  border: 1px solid rgba(246, 224, 202, 0.3);
  border-radius: 15px;
  color: rgba(246, 224, 202, 0.8);
  font-size: 14px;
  padding: 8px 20px;
  cursor: pointer;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}
</style>
